package net.wangds.poi.comp;

import net.wangds.log.helper.LogHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.io.InputStream;
import java.util.function.Consumer;

public abstract class AbstractExcelComp {

    /**
     * 读取Excel文件.
     * @param is 流.
     * @return Excel工作簿.
     * @throws IOException 读取异常.
     */
    protected abstract Workbook loadWorkbook(InputStream is) throws IOException;

    /**
     * 读取工作簿.
     * @param rsc 文件簿资源.
     * @return 发生异常时为"<code>null</code>".
     */
    public Workbook loadWorkbook(Resource rsc){
        if(rsc==null){
            return null;
        }

        Workbook res = null;
        try(InputStream is = rsc.getInputStream()){
            res = loadWorkbook(is);
        } catch (IOException e) {
            LogHelper.error(e);
        }
        return res;

    }

    /**
     * 读取工作表.
     * @param rsc 资源.
     * @param onSuccess 成功回调.
     * @param onExeption 异常回调.
     */
    public void onWorkbook(Resource rsc, Consumer<Workbook> onSuccess, Consumer<Exception> onExeption){
        if(rsc==null){
            LogHelper.warn("读取Excel文件时资源文件参数为null.");
            return;
        }

        if(onSuccess!=null) {
            try (InputStream is = rsc.getInputStream()) {
                onSuccess.accept(loadWorkbook(is));
            } catch (IOException e) {
                if(onExeption!=null){
                    onExeption.accept(e);
                }else {
                    LogHelper.error(e);
                }
            }
        }

    }

    public void withWorkbook(Workbook wb, Consumer<Workbook> callback, Consumer<IOException> onException){
        if(wb!=null && callback!=null){
            try(Workbook c=wb){
                callback.accept(wb);
            } catch (IOException e) {
                if(onException!=null){
                    onException.accept(e);
                }else{
                    LogHelper.error(e);
                }
            }
        }
    }

    public void withSheet(Workbook workbook, int sheetNo, Consumer<Sheet> callback, Consumer<IOException> onException){
        withWorkbook(workbook,(wb)->{
            Sheet sheet = wb.getSheetAt(sheetNo);
            if(sheet!=null){
                if(callback!=null){
                    callback.accept(sheet);
                }
            }
        }, onException);
    }

}
